package com.qctpos.crm.dao.config;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.util.*;


@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@Slf4j
public class OptimisticLockerExceptionInterceptor implements Interceptor {


    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        Object param = args[1];
        if (param instanceof Map)
        {
            Map map = (Map) param;
            MappedStatement ms = (MappedStatement) args[0];
            String methodName = ms.getId().substring(ms.getId().lastIndexOf(".") + 1);
            //只限制通过updateById 才验证乐观锁
            if (SqlCommandType.UPDATE != ms.getSqlCommandType() || !"updateById".equals(methodName))
            {
                //update 方法在这里判断如果没带条件则 不让执行 应为会更新全表
                if ("update".equals(methodName))
                {
                    AbstractWrapper<?, ?, ?> aw = (AbstractWrapper)map.getOrDefault("ew", (Object)null);
                    if (aw == null)
                    {
                        throw new RuntimeException("update更新请传条件");
                    }
                }
                return invocation.proceed();
            }

            Object et = map.getOrDefault("et",null);
            if (et == null)
            {
                return invocation.proceed();
            }

            TableInfo tableInfo = TableInfoHelper.getTableInfo(et.getClass());
            if (tableInfo == null || !tableInfo.isWithVersion()) {
                return invocation.proceed();
            }
            TableFieldInfo fieldInfo = tableInfo.getVersionFieldInfo();
            Field versionField = fieldInfo.getField();
            Object originalVersionVal = versionField.get(et);
            if (originalVersionVal == null) {
                throw new RuntimeException("原乐观锁数据为空");
            }

            Object updatedVersionVal = (Integer)originalVersionVal + 1;
            map.put("MP_OPTLOCK_VERSION_ORIGINAL", originalVersionVal);
            versionField.set(et, updatedVersionVal);
            // 更新结果
            Object resultObj = invocation.proceed();
            if (resultObj != null && resultObj instanceof Integer && ((Integer) resultObj)==0)
            {
               throw new RuntimeException("数据已被修改");
            }
            return resultObj;
        }
        else
        {
            return invocation.proceed();
        }

    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }
    @Override
    public void setProperties(Properties properties) {
        // to do nothing
    }
}
